<template>
	<div class='personalCenterContainer'>
		<div class="personalCenterContent">
			<div class="left">
				<div class='title'>{{t('personalInformation','编辑信息')}}</div>
				<div class='home_aside_information'>
					<div class='edit_password'>
						<div class='home_aside_information_item'>
							<span>{{t('personalInformation','姓名')}}</span>：
							<span id="">{{userData.name||''}}</span>
						</div>
						<!-- <a-button type="primary" @click='()=>editPasswordOpen=true' style='margin-left:40px;'>修改密码</a-button> -->
					</div>
					<template v-if='!isTeacher()'>
						<div class='home_aside_information_item'>
							<span>{{t('personalInformation','学号')}}</span>：
							<span id="">{{userData.num||''}}</span>
						</div>
						<div class='home_aside_information_item'>
							<span>{{t('personalInformation','年级')}}</span>：
							<span id="">{{userData.gradeName||''}}</span>
						</div>
						<div class='home_aside_information_item'>
							<span>{{t('personalInformation','班级')}}</span>：
							<span v-if="userData && userData.gradeClasses && userData.gradeClasses.length > 0">
								{{ userData.gradeClasses[0].name || t('common','暂无') }}
							</span>
							<span v-else>暂无班级</span>
						</div>
						<div class='home_aside_information_item'>
							<span>{{t('personalInformation','专业方向')}}</span>：
							<span v-if="userData && userData.gradeClasses && userData.gradeClasses.length > 0">
									{{ userData.gradeClasses[0].professionalDirection || t('common','暂无') }}
							</span>
							<span v-else>{{t('common','暂无')}}</span>
						</div>
					</template>

					<template v-if='isTeacher()'>
						<div class='home_aside_information_item'>
							<span>{{t('personalInformation','手机号')}}</span>：
							<span id="">{{userData.mobile||''}}</span>
						</div>
					</template>

				</div>
				
				<template v-if='!isTeacher()'>
					<div class='editItem'>
						<div class='editItem_label'>{{t('personalInformation','邮箱')}}：</div>
						<a-input v-model:value="userData.email" :placeholder="t('personalInformation','请输入邮箱')" style='max-width: 400px;' />
					</div>
					<div class='editItem'>
						<div class='editItem_label'>{{t('personalInformation','手机号')}}：</div>
						<a-input v-model:value="userData.mobile" :placeholder="t('personalInformation','请输入手机号')" style='max-width: 400px;' />
					</div>
					<!-- <div class='editItem'>
						<div class='editItem_label'>{{t('personalInformation','QQ号')}}：</div>
						<a-input v-model:value="userData.qq" :placeholder="t('personalInformation','请输入QQ号')" style='max-width: 400px;' />
					</div> -->
					<div class='editItem'>
						<div class='editItem_label'>{{t('personalInformation','自我介绍')}}：</div>
						<a-textarea v-model:value="userData.introduceYourself" :placeholder="t('personalInformation','请输入自我介绍')" :rows="4"
							style='max-width: 400px;' />
					</div>
				</template>
				
				<template v-if='isTeacher()'>
				
					<div class='editItem'>
						<div class='editItem_label'>{{t('personalInformation','专业方向')}}：</div>
						<a-input v-model:value="userData.orientation" :placeholder="t('personalInformation','请输入专业方向')" style='max-width: 400px;' />
					</div>
					<div class='editItem'>
						<div class='editItem_label'>{{t('personalInformation','自我介绍')}}：</div>
						<a-textarea v-model:value="userData.introduceYourself" :placeholder="t('personalInformation','请输入自我介绍')" :rows="4"
							style='max-width: 400px;' />
					</div>
				</template>

				<div class='btnBox'>
					<a-button style="margin-right:10px" @click='cancel'>{{t('common','取消')}}</a-button>
					<a-button style="margin-right:10px" type="primary" @click='save'>{{t('common','保存')}}</a-button>
					<a-button @click='toHome'>{{t('personalInformation','返回首页')}}</a-button>
				</div>
			</div>
			<div class="right">
				<div class="info">
					<div class="avatar">
						<img :src="userData.avatarUrl || avatar" alt="">
					</div>
					<minFile @handleReadFile="handleReadFile">
						<div class="edit">{{t('personalInformation','编辑')}}</div>
					</minFile>
					
				</div>
				<div class="name">{{userData.name||''}}</div>
				<div class="btn" @click="handleClick({name: '修改密码'})">{{t('personalInformation','修改密码')}}</div>
			</div>
		</div>

		<a-modal v-model:open="editPasswordOpen" :title="t('personalInformation','修改密码')" @cancel='clear' @ok='submit'>
			<a-form :model="formState" name="normal_login" class="login-form" :rules='rules' ref="formRef"
				@submit="submit">
				<a-form-item has-feedback name="oldPassword">
					<a-input-password v-model:value="formState.oldPassword" type="password" :placeholder="t('login','请输入旧密码')" />
				</a-form-item>
				<a-form-item has-feedback name="newPassword">
					<a-input-password v-model:value="formState.newPassword" type="password" autocomplete="off"
						:placeholder="t('login','请输入新密码')" />
				</a-form-item>
				<a-form-item has-feedback name="verifyPassword">
					<a-input-password v-model:value="formState.verifyPassword" type="password" autocomplete="off"
						:placeholder="t('login','请再次输入新密码')" />
				</a-form-item>
			</a-form>
		</a-modal>
	</div>

</template>

<script setup>
import minFile from '@/components/common/minFile.vue'
import avatar from '@/assets/user.png'
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		modifyStudentInformation,
		getStudentInformation,
		getTeacherInformation,
		modifyTeacherInformation,
		stuUploadAvatar
	} from '@/request/personalCenter.js'
	
	import {
		state
	} from '@/stores/info.js'
	import {
		message
	} from 'ant-design-vue';
	import {
		modifyPassword
	} from '@/request/login.js'
	import {
		isTeacher
	} from "@/stores/info"
import { useRouter, useRoute } from 'vue-router'
import { t } from '@/i18n'

const formRef = ref(null)
const router = useRouter()
function toHome(){
	router.push({name: 'stu'})
}

	onMounted(async () => {
		 console.log('Personal Information Component Mounted');
		await getStudentMessage()
	})
	//修改密码
	let editPasswordOpen = ref(false)
	const formState = reactive({
		oldPassword: '',
		newPassword: '',
		verifyPassword: '',
	});
	//清空
	function clear() {
		for (let key in formState) {
			formState[key] = ''
		}
		editPasswordOpen.value = false
	}
	const handleClick = ({name}) =>{
	switch (name) {
		case '修改密码':
			formState.value = {}
			editPasswordOpen.value = true
			formRef.value?.resetFields()
			break
	}
}
	//点击修改密码按钮
	async function submit() {
		let data = {}
		let res = await modifyPassword(formState)
		console.log('修改密码', res)
		if (res && res.code && res.code == 200) {
			message.success(res.data ? res.data.message : t('login','密码修改成功'));
			clear()
			// editPasswordOpen.value = false
		} else {
			message.error(res.data ? res.data.message : t('login','密码修改失败，请重试'));
			clear()
			// editPasswordOpen.value = false
		}
	}

	//两次密码校验
	const validatePass = async (_rule, value) => {
		if (value === '') {
			return Promise.reject(t('login','请输入新密码'));
		} else if (value.length < 6 || value.length > 16) {
			return Promise.reject(t('login','密码长度必须在6-16位之间'));
		}
		// else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/.test(value)) {
		//   return Promise.reject('密码必须包含数字和字母');
		// }
		else {
			return Promise.resolve();
		}
	};
	const validatePass2 = async (_rule, value) => {
		if (value === '') {
			return Promise.reject(t('login','请再次输入新密码'));
		} else if (value !== formState.newPassword) {
			return Promise.reject(t('login',"两次密码不匹配!"));
		} else if (value.length < 6 || value.length > 16) {
			return Promise.reject(t('login','密码长度必须在6-16位之间'));
		}
		// else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/.test(value)) {
		//   return Promise.reject('密码必须包含数字和字母');
		// }
		else {
			return Promise.resolve();
		}
	}
	const rules = {
		oldPassword: [{
			required: true,
			trigger: 'change',
			validator: validatePass,
			message: t('login','请输入旧密码'),
		}],
		newPassword: [{
			required: true,
			validator: validatePass,
			trigger: 'change',
			message: t('login','请输入新密码'),
		}],
		verifyPassword: [{
			required: true,
			validator: validatePass2,
			trigger: 'change',
			message: t('login','请再次输入新密码'),
		}],
	}
	


	//修改基本信息
	let userData = reactive(state.userInfo)
	let userData2 = reactive({})
	async function getStudentMessage() {
		let res
		if(isTeacher()){
			res = await getTeacherInformation()
		}else{
			res = await getStudentInformation()
		}
		console.log('基本信息',res)
		if (res&&res.code == 200) {
			for (let key in res.data) {
				userData[key] = res.data[key] != 'null' && res.data[key] ? res.data[key] : ''
				userData2[key] = res.data[key] != 'null' && res.data[key] ? res.data[key] : ''

			}
			
		}
	}

	function cancel() {
		console.log('userData2', userData2)
		for (let key in userData2) {
			userData[key] = userData2[key]
		}
	}
	async function save() {
		let formData = new FormData()

		let data = {
			email: userData.email,
			mobile: userData.mobile,
			qq: userData.qq,
			introduceYourself: userData.introduceYourself
		}
		for (let key in data) {
			formData.append(key, data[key])
		}
		console.log('修改的数据', data)
		let res = await modifyStudentInformation(formData);
		if (res&&res.code == 200) {
			message.success(t('login','信息修改成功'))

			await getStudentMessage()
		}
		console.log('修改', res)

	}
	const handleReadFile = async (e) => {
		if (e.message) return message.error(e.message)
		let res = await stuUploadAvatar({ file: e.file })
		if (!res) return
		message.success(t('common','上传成功'))
		userData['avatarUrl'] = res.data
		state.userInfo.avatarUrl=userData['avatarUrl']
		localStorage.setItem('userInfo',JSON.stringify(state.userInfo))

	}
</script>

<style lang='scss' scoped>
	@import '@/styles/public.scss';
	$informationContainerPaddingTop:20px;
	$informationContainerPaddingLeft:30px;

	.personalCenterContainer {
		height: calc(100% - #{$foundationContentPadding} * 2);
		/* width: calc(100% - #{$foundationContentPadding} * 2); */
		width: 800px;
		margin: $foundationContentPadding;
		background-color: white;
		border-radius: 10px;
		position: relative;
		padding: $informationContainerPaddingTop $informationContainerPaddingLeft;

		.title {
			font-size: 18px;
			font-weight: bold;
			margin-bottom: 15px;
		}

		.home_aside_information {
			width: 100%;
			margin-bottom: 10px;
			/* padding-bottom:42px; */
			/* height: 100%; */

			.edit_password {
				display: flex;
				align-items: baseline;
			}

			.home_aside_information_item {
				/* width: 70%; */
				/* display: flex;
				align-items: center; */
				height: 28px;
				margin: 10px 0 0 0;
				min-width: 100px;
				line-height: 28px;
			}
		}

		.editItem {
			display: flex;
			flex-direction: column;
			/* align-items: center; */
			/* margin-bottom: 8px; */

			.editItem_label {
				// width: 80px;
				display: flex;
				align-items: center;
				/* margin-top: 12px; */
				margin-bottom: 10px;
			}
		}

		.editItem:nth-last-child(1) {
			margin-bottom: 0px;
		}

		.btnBox {
			// width: 320px;
			margin: 0 $informationContainerPaddingLeft $informationContainerPaddingTop 0;
			position: absolute;
			bottom: 0;
			right: 0;
			// display: flex;
			// justify-content: space-between;
		}
	}

	.personalCenterContent {
    flex-grow: 1;
		align-self: stretch;
			display: flex;
		.left {
			width: 400px;

			display: flex;
			flex-direction: column;
			gap: 18px;
			.item {
				display: flex;
				align-items: center;
				.label {
					font-weight: 400;
					font-size: 14px;
					color: rgba(0,0,0,0.85);
					margin-right:10px;
				}
			}
			.customItem {
				display: flex;
				flex-direction: column;
				.label {
					font-weight: 400;
					font-size: 14px;
					color: rgba(0,0,0,0.85);
				}
				.value {
					margin-top: 10px;
				}
			}
			
		}
		.right {
			width: 400px;
			display: flex;
			align-items: center;
			padding-top: 50px;
			flex-direction: column;
			.info {
				width: 106px;
				height: 106px;
				display: flex;
					flex-direction: column;
					align-items: center;
				.avatar {
					width: 100%;
					height: 100%;
					border-radius: 50%;
					overflow: hidden;

					img {
						width: 100%;
						height:100%;
						object-fit: cover;
					}
				}
				
				.edit {
					margin-top: -10px;
					width: 40px;
					height: 18px;
					background: rgba(0,0,0,0.63);
					border-radius: 9px;
					display: flex;
					align-items: center;
					justify-content: center;
					font-weight: 500;
					font-size: 12px;
					color: #FFFFFF;
					cursor: pointer;

				}
			}
			.name {
				margin-top: 15px;
				font-weight: 500;
				font-size: 20px;
				color: rgba(0,0,0,0.85);
			}
			.btn {
				cursor: pointer;
				margin-top: 8px;
				// width: 60px;
				padding:5px;
				height: 26px;
				background: #EEEEFF;
				border-radius: 6px;
				border: 1px solid #D7D5FF;
				display: flex;
				align-items: center;
				justify-content: center;
				font-weight: 400;
				font-size: 12px;
				color: #8466F5;
			}
		}

  }
</style>
